//以链表为基础实现的栈结构

class LinkedStack {
    constructor() {
        //定义节点
        class Node {
            constructor(val) {
                this.val = val;
                this.next = null;
            }
        }

        var length = 0; 
        var top;  //栈顶指针

        //入栈	
        this.push = function (val) {
            var node = new Node(val);
            if (!top) {
                top = node;
                length++;
                return true;
            } else {
                node.next = top;
                top = node;
                length++;
                return true;
            }
        };
        //出栈
        this.pop = function () {
            var current = top;
            if (top) {
                top = current.next;
                current.next = null;
                length--;
                return current;
            } else {
                return false;
            }
        };
        //获取栈顶节点
        this.top = function () {
            return top;
        };
        //获取栈长
        this.size = function () {
            return length;
        };

        //打印栈内元素
        this.toString = function () {
            var string = '', current = top;

            while (current) {
                string += current.val;
                current = current.next;
            }

            return string;
        };
        //清空栈
        this.clear = function () {
            top = null;
            length = 0;

            return true;
        };
    }
}

let stack = new LinkedStack;
stack.push(6);
stack.push(9);
stack.push(7);
console.log(stack.size()); // 3
console.log(stack.toString()); // 7,9,6
console.log(stack.clear()); //ture
console.log(stack.toString());  //空